#include <IRremote.h>        // Must be located in sketchbook
                    //  libraries folder

int RECV_PIN = 13;
int lampPin[] = {2,3,4,5,6,7,8,9,10,11};
int lampSize = 10;
String lampStatus[] = {"f","f","f","f","f","f","f","f","f","f"};
IRrecv irrecv(RECV_PIN);
decode_results results;
int numPadSize = 11;
String irData[] = {"30cf","8f7","8877","48b7","28d7","a857","6897","18e7","9867","58a7","ff"};
int resultData[] = {0,1,2,3,4,5,6,7,8,9,99};
char inData[20];
String serialDataStarter = "~";
String serialDataEnder = "|";
char inChar=-1;
boolean isListen = false;
int index =0;

void setup() {
  Serial.begin(9600);
  irrecv.enableIRIn();        // Start the receiver
  initPin();
}

void loop() {
  IrcLoop();
  SerialLoop();
}

void SerialLoop(){
  if(Serial.available() > 0) {
      inChar = Serial.read();
      String str(inChar);
      if(serialDataStarter.equals(str)){
       isListen= true;
      }
      else if(serialDataEnder.equals(str)){
        isListen = false;
        Serial.println(inData);
        String code(inData);
         lampAction(0);
        index = 0;
      }
      if(isListen){
       inData[index] = inChar;
       inData[index+1] ='\0';
      index++; 
      }
    }
  }

void IrcLoop(){
 if (irrecv.decode(&results)) {
    Serial.print("Received :");
    //Serial.println(results.value, HEX);
    Serial.println(irDataToInt(results.value));
    Serial.println(results.value);
    lampAction(irDataIndex(results.value));
    irrecv.resume();          // Receive the next value
  }
}

String toHex (int value){
 return String(value, HEX);  
}
void lampAction(int irDataIndex){
      if(resultData[irDataIndex] == 99){
        int a =0;
        for(a = 0; a < lampSize; a++){
          digitalWrite(lampPin[a], LOW);
          lampStatus[a] = "f";
        }
      }
      else if(lampStatus[irDataIndex] == "t"){
        digitalWrite(lampPin[irDataIndex], LOW);
        lampStatus[irDataIndex] = "f";
      }else{
        digitalWrite(lampPin[irDataIndex], HIGH);
        lampStatus[irDataIndex] = "t";
      }
}

int serialDataIndex(String _code){
  Serial.print("Code :");
  Serial.println(_code);
  int a = 0;
  for( a = 0; a < numPadSize ; a++){
    if(_code == irData[a]){
      return a;
    }
  }
  return -1;
}

int irDataIndex(int value){
  String _code = toHex(value);
  Serial.print("Code :");
  Serial.println(_code);
  int a = 0;
  for( a = 0; a < numPadSize ; a++){
    if(_code == irData[a]){
      return a;
    }
  }
  return -1;
}
void initPin(){
  int a =0;
  for( a = 0; a < numPadSize ; a++){
    pinMode(lampPin[a], OUTPUT);
    digitalWrite(lampPin[a], LOW);
  }
}

int irDataToInt(int value){
  String _code = toHex(value);
  int a = 0;
  for( a = 0; a < numPadSize ; a++){
    if(_code == irData[a]){
      return resultData[a];
    }
  }
  return -1;
}

